/**************************************************************************
 * @file BC_QC_PHY.c
 * @author BryanHe(贺璧) (532352406@qq.com)
 * @brief
 * @version 0.1
 * @date 2025-08-18
 *
 * @copyright Copyright (c) 2025
 *
 *************************************************************************/
#include "system.h"
#include "BC_QC_PHY.h"

UINT16 Check_ADC(UINT8 ch) {
    UINT16 ret;
    ADC_ChSelect(ch);                 /* 选择通道 */
    ADC_StartSample();                /* 启动采样 */
    while ((ADC_CTRL & bADC_IF) == 0); /* 等待转换完成 */

    ADC_CTRL |= bADC_IF; /* 清标志 */
    ret = (UINT16)ADC_DAT;
    // my_printf("ch:%d\n",(UINT16)ch);                    /* 输出ADC采样值 */
    // my_printf("value:%d\n",(UINT16)ret);
    return ret;
}

/*******************************************************************************
 * Function Name  : void BC1_2Check(void)
 * Description    : BC1.2检测
 *******************************************************************************/
BC_TYPE_T BC1_2Check(void) {
    BC_TYPE_T bc_type = BC_TYPE_UN_KNOWN;
    UINT8 CheckCount;

    USB_DP_OUT_0v6();
    CheckCount = 40;
    // my_printf("BC1_2Check\r\n", 0);

    while (CheckCount) {
        if (Check_ADC(DMAisle) >= Volt0_3) {
            bc_type = BC_T_CDP_OR_DCP;
        } else {
            bc_type = BC_TYPE_SDP;
        }
        CheckCount--;
        mDelaymS(1);
    }

    if (bc_type == BC_T_CDP_OR_DCP) {
        USB_DM_OUT_0v6();
        CheckCount = 40;
        bc_type = BC_TYPE_UN_KNOWN;
        while (CheckCount) {
            if (Check_ADC(DPAisle) >= Volt0_3) {
                bc_type = BC_TYPE_DCP;
            } else {
                bc_type = BC_TYPE_CDP;
            }
            CheckCount--;
            mDelaymS(1);
        }
        if (bc_type == BC_TYPE_DCP) {
            USB_DP_OUT_0v6();
            bc_type = BC_TYPE_UN_KNOWN;
            CheckCount = 150;
            while (CheckCount) {
                if (Check_ADC(DMAisle) <= Volt0_3) {
                    my_printf("This is DCP\r\n", 0);
                    bc_type = BC_TYPE_DCP;
                    break;
                }
                CheckCount--;
                mDelaymS(30);
            }
        } else {
            my_printf("This is CDP\r\n", 0);
            bc_type = BC_TYPE_CDP;
        }
    } else {
        my_printf("This is SDP\r\n", 0);
        bc_type = BC_TYPE_SDP;
    }

    // my_printf("BC1.2 finished\r\n",0);
    return bc_type;
}
